package com.xltq.filter;

import com.xltq.entity.User;
import com.xltq.service.IUserService;
import com.xltq.service.impl.IUserServiceImpl;
import com.xltq.utils.Base64Utils;
import com.xltq.utils.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebFilter("/login.jsp")
public class AutoFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //自动登录放行过滤操作
        HttpServletRequest request = (HttpServletRequest) req;
        //通过请求对象获取cookie值
        Cookie[] cookies = request.getCookies();
        if (Objects.nonNull(cookies)) {
            //只要不为null就证明数据存了
            String content = null;//用户存储cookie中存储的用户和密码
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(Constants.AUTO_NAME)) {
                    content = cookie.getValue();
                }
            }
            if (Objects.nonNull(content)) {
                //将存储子啊content中用户名和密码进行Base64转码
                content = Base64Utils.decode(content);
                //username:password 获取content数据
                //拆分数据获取具体的用户名和密码
                String[] split = content.split(Constants.FLAG);
                String username = split[0];
                String password = split[1];
                //调用service进行登录操作
                IUserService userService = new IUserServiceImpl();

                try {
                    User user = userService.login(username, password);
                    if (Objects.nonNull(user)) {
                        //可以自动刚登录
                        //向header.jsp页面中更实用 loginUser key中存数据以作为页面展示
                        //用户名|注销  而不是 登录|注册
                        request.getSession().setAttribute("loginUser", user);
                        HttpServletResponse response = (HttpServletResponse) resp;
                        response.sendRedirect(request.getContextPath() + "/index.jsp");
                    } else {
                        chain.doFilter(req, resp);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                //cookie中获取content没有数据 放行
                chain.doFilter(req, resp);
            }
        } else {
            //没有cookie 放行
            chain.doFilter(req, resp);
        }

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
